<template>
	<ppl-navbar title="校园兼职" bgColor="#E3EEFF">
		<view @click="back">
			<van-icon name="arrow-left" size="40rpx" />
		</view>
	</ppl-navbar>
	<view class="wrapper bg-linear">
		<!-- 加载状态 -->
		<view v-if="isLoading" class="loading">加载中...</view>
		<!-- 空状态 -->
		<view v-else-if="LDlists.length === 0" class="empty-state">暂无兼职信息</view>
		<!-- 兼职列表 -->
		<view v-else>
			<view v-for="(item, index) in LDlists" class="list-item bg-color boder-r-10 m-b-12 shadow1" :key="item.id"
				@click="toDetail(item)">
				<view class="p-b-14 t-bold">{{ item.title }}</view>
				<view class="item-content ellipsis">{{ item.requirements }}</view>
				<view class="t-12 color4">{{ item.updateTime || item.createTime }}</view>
			</view>
			<!-- 加载更多提示 -->
			<view v-if="isLoadingMore" class="load-more">加载更多...</view>
			<view v-else-if="hasMore" class="load-more-tip">上拉加载更多</view>
			<view v-else class="load-more-tip">没有更多数据了</view>
		</view>
	</view>
	<view>
		<view class="issue-button" @click="toIssue">
			<van-image width="160rpx" height="160rpx" src="../../../static/image/issue.png" />
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import {
		ref,
		watch
	} from 'vue';
	import {
		getCampusPartTimeJobListBySchoolId
	} from '@/package/api/selList.js';

	const LDlists = ref([]);
	const schoolId = ref(null);
	const page = ref(1); // 当前页码
	const pageSize = ref(10); // 每页数据量
	const hasMore = ref(true); // 是否还有更多数据
	const isLoading = ref(true); // 初始加载状态
	const isLoadingMore = ref(false); // 加载更多状态

	// 显示提示信息
	const showToast = (title, icon = 'none') => {
		uni.showToast({
			title,
			icon,
			duration: 2000
		});
	};

	// 从本地存储获取学校ID
	const getSchoolIdFromStorage = () => {
		try {
			// 从本地存储获取school_id
			const schoolIdValue = uni.getStorageSync('school_id');
			if (schoolIdValue) {
				schoolId.value = schoolIdValue;
				return true;
			}
			showToast('获取学校ID失败，请检查登录状态', 'error');
			return false;
		} catch (error) {
			console.error('获取本地存储学校ID错误:', error);
			showToast('获取学校ID异常，请稍后重试', 'error');
			return false;
		}
	};

	// 加载数据
	const loadData = (isRefresh = false) => {
		if (!schoolId.value) {
			if (!getSchoolIdFromStorage()) {
				isLoading.value = false;
				return;
			}
		}

		if (isRefresh) {
			page.value = 1;
			LDlists.value = [];
		}

		isLoading.value = true;
		isLoadingMore.value = true;

		// 构造请求参数
		const params = {
			schoolId: schoolId.value,
			page: page.value,
			pageSize: pageSize.value
		};

		// 优先从本地存储获取数据（如果有）
		const cachedData = uni.getStorageSync('campusPartTimeJobs');
		if (cachedData && cachedData.length > 0) {
			processCachedData(cachedData, isRefresh);
			isLoading.value = false;
			isLoadingMore.value = false;
			return;
		}
		const data = {
			schoolId: uni.getStorageSync('school_id')
		};

		// 调用后台API获取数据
		getCampusPartTimeJobListBySchoolId(JSON.stringify(data))
			.then(res => {
				if (res.code === 200 && res.data && res.data.length > 0) {
					// 处理获取到的数据
					if (isRefresh) {
						LDlists.value = res.data;
					} else {
						LDlists.value = [...LDlists.value, ...res.data];
					}

					// 缓存数据到本地存储
					if (isRefresh) {
						uni.setStorageSync('campusPartTimeJobs', res.data);
					}

					// 判断是否还有更多数据
					hasMore.value = res.data.length === pageSize.value;
				} else {
					hasMore.value = false;
					if (isRefresh) {
						LDlists.value = [];
					}
				}
			})
			.catch(error => {
				console.error('获取兼职数据失败:', error);
				showToast('获取兼职信息失败，请稍后重试', 'error');
				// 尝试从本地缓存获取数据
				const cachedData = uni.getStorageSync('campusPartTimeJobs');
				if (cachedData && cachedData.length > 0) {
					processCachedData(cachedData, isRefresh);
				} else if (isRefresh) {
					LDlists.value = [];
				}
			})
			.finally(() => {
				isLoading.value = false;
				isLoadingMore.value = false;

				// 结束下拉刷新
				if (isRefresh) {
					uni.stopPullDownRefresh();
				}
			});
	};

	// 处理缓存数据
	const processCachedData = (data, isRefresh) => {
		if (isRefresh) {
			LDlists.value = data;
		} else {
			LDlists.value = [...LDlists.value, ...data];
		}
		hasMore.value = false; // 缓存数据不支持加载更多
	};

	// 监听schoolId变化，重新加载数据
	watch(schoolId, (newId, oldId) => {
		if (newId && newId !== oldId) {
			loadData(true);
		}
	});

	onLoad((e) => {
		// 先尝试从本地存储获取学校ID
		getSchoolIdFromStorage();
		loadData(true);
	});

	onShow(() => {
		// 页面显示时重新获取数据
		loadData(true);
	});

	// 无限加载 - 页面滚动到底部时触发
	onReachBottom(() => {
		if (hasMore.value && !isLoadingMore.value) {
			page.value++;
			loadData();
		}
	});

	// 下拉刷新 - 页面下拉时触发
	onPullDownRefresh(() => {
		loadData(true);
	});

	const back = () => {
		uni.navigateBack();
	};

	const toIssue = () => {
		uni.navigateTo({
			url: '/package/pages/issueShortShift/issueShortShift'
		});
	};

	// 修改toDetail函数，接收整个item对象并存储到本地
	const toDetail = (item) => {
		console.log("------------------");
		console.log("点击的兼职数据:", item);
		try {
			// 将当前点击的兼职详情存入本地存储
			uni.setStorageSync('currentJobDetail', item);
			console.log("存储的兼职数据:", uni.getStorageSync('currentJobDetail'));
			// 跳转到详情页
			uni.navigateTo({
				url: `/package/pages/shortShiftDetail/shortShiftDetail?id=${item.id}`
			});
		} catch (error) {
			console.error('存储兼职详情失败:', error);
			showToast('获取详情失败，请稍后重试', 'error');
		}
	};
</script>

<style scoped>
	.list-item {
		padding: 40rpx 30rpx;
		background-color: #fff;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.item-content {
		padding-bottom: 20rpx;
		color: #333;
		font-size: 28rpx;
		line-height: 1.5;
	}

	.issue-button {
		position: fixed;
		right: 30rpx;
		bottom: 100rpx;
		z-index: 100;
	}

	.loading,
	.empty-state {
		text-align: center;
		padding: 80rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.load-more,
	.load-more-tip {
		text-align: center;
		padding: 30rpx 0;
		color: #999;
		font-size: 24rpx;
	}

	/* 内容超过一行显示省略号 */
	.ellipsis {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
</style>